package xiaozhi.modules.security.oauth2;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import xiaozhi.common.utils.HttpContextUtils;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.security.service.ShiroService;

import java.util.HashMap;
import java.util.Map;

/**
 * 第三方API访问认证过滤器
 * 用于处理第三方平台的API访问认证
 */
public class ThirdPartyApiFilter extends AuthenticatingFilter {
    
    private final ShiroService shiroService;
    
    public ThirdPartyApiFilter(ShiroService shiroService) {
        this.shiroService = shiroService;
    }
    
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        // 从请求头中获取API Key
        String apiKey = getApiKey((HttpServletRequest) request);
        
        if (StringUtils.isBlank(apiKey)) {
            return null;
        }
        
        return new ThirdPartyAuthenticationToken(apiKey);
    }
    
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 允许跨域请求中的预检请求
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        
        return false;
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 从请求头中获取API Key
        String apiKey = getApiKey((HttpServletRequest) request);
        
        if (StringUtils.isBlank(apiKey)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
            
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> result = new HashMap<>();
            result.put("code", HttpStatus.UNAUTHORIZED.value());
            result.put("msg", "缺少API Key，请在请求头中添加 X-API-KEY");
            
            String json = objectMapper.writeValueAsString(result);
            httpResponse.getWriter().print(json);
            
            return false;
        }
        
        return executeLogin(request, response);
    }
    
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();
        result.put("code", HttpStatus.UNAUTHORIZED.value());
        result.put("msg", "API Key认证失败");
        
        try {
            String json = objectMapper.writeValueAsString(result);
            httpResponse.getWriter().print(json);
        } catch (Exception ignored) {
            
        }
        
        return false;
    }
    
    /**
     * 获取请求中的API Key
     */
    private String getApiKey(HttpServletRequest httpRequest) {
        // 从请求头中获取
        String apiKey = httpRequest.getHeader("X-API-KEY");
        
        // 如果请求头中没有，从请求参数中获取
        if (StringUtils.isBlank(apiKey)) {
            apiKey = httpRequest.getParameter("api_key");
        }
        
        return apiKey;
    }
}